<template>
  <view>
    <s-layout :onShareAppMessage="shareInfo" navbar="goods">
      <!-- 下架/不可用提醒 -->
      <s-empty
        v-if="state.coachInfo === null"
        text="教练不存在或已下架"
        icon="/static/soldout-empty.png"
        showAction
        actionText="再看看"
        actionUrl="/pages/index/index"
      />
      <block v-else>
        <view class="detail-swiper-selector">
          <!-- 教练轮播图  -->
          <su-swiper
            class="ss-m-b-14"
            isPreview
            :list="formatGoodsSwiper(state.coachInfo.sliderPicUrls)"
            otStyle="tag"
            imageMode="widthFix"
            dotCur="bg-mask-40"
            :seizeHeight="750"
          />
          
          <!-- 教练信息卡片 -->
          <view class="coach-card detail-card ss-p-y-30 ss-p-x-20">
            <view class="ss-flex ss-row-between ss-col-center ss-m-b-26">
              <view class="coach-info ss-flex ss-col-center">
                <image class="coach-avatar" :src="sheep.$url.cdn(state.coachInfo.picUrl)" />
                <view class="coach-details ss-m-l-20">
                  <view class="coach-name">{{ state.coachInfo.name }}</view>
                  <view class="coach-experience">{{ state.coachInfo.introduction }}</view>
                  <view class="coach-rating ss-flex ss-col-center ss-m-t-10">
                    <view class="rating-stars ss-flex ss-col-center">
                      <text class="star-icon" v-for="i in 5" :key="i" 
                        :class="{ 'active': i <= Math.floor(5) }">★</text>
                    </view>
                    <text class="rating-text ss-m-l-10">5.0分</text>
                    <text class="student-count ss-m-l-20">已带学员{{ formatSales('exact', state.coachInfo.salesCount) }}</text>
                  </view>
                </view>
              </view>
              <view class="price-box ss-flex ss-col-bottom">
                <view class="price-text ss-m-r-16">
                  {{ fen2yuan(state.selectedSku.price || state.coachInfo.price) }}
                </view>
                <view class="price-unit">/课时</view>
              </view>
            </view>
            
            <!-- 教练标签 -->
            <view class="coach-tags ss-flex ss-m-b-20">
              <view class="tag">经验丰富</view>
              <view class="tag">通过率高</view>
              <view class="tag">耐心细致</view>
              <view class="tag">因材施教</view>
            </view>
          </view>

          <!-- 功能卡片 -->
          <view class="detail-cell-card detail-card ss-flex-col">
            <view class="cell-box ss-flex ss-row-between ss-col-center" @tap="state.showTimeSelect = true">
              <view class="cell-mmm">
                <view class="cell-title">预约时间</view>
                <view class="cell-desc ss-line-1">
                  {{ getSelectedTimesText() }}
                </view>
              </view>
              <text class="cicon-forward"></text>
            </view>
          </view>

          <!-- 预约时间选择弹框 -->
          <su-popup
            :show="state.showTimeSelect"
            type="bottom"
            round="20"
            :isMaskClick="true"
            @close="state.showTimeSelect = false"
          >
            <view class="time-select-popup">
              <view class="popup-header ss-flex ss-row-between ss-col-center ss-p-x-30 ss-p-y-20">
                <text class="popup-title">选择预约时间</text>
                <text class="close-btn" @tap="state.showTimeSelect = false">✕</text>
              </view>
              <view class="time-content ss-p-30">
                <!-- 日期选择 -->
                <view class="date-selector ss-m-b-30">
                  <view class="date-title ss-m-b-20">选择预约日期</view>
                  <scroll-view class="date-scroll" scroll-x>
                    <view class="date-list ss-flex">
                      <view
                        v-for="(date, index) in state.availableDates"
                        :key="index"
                        class="date-item"
                        :class="{ 'active': state.selectedDate === date.value }"
                        @tap="selectDate(date.value)"
                      >
                        <view class="date-day">{{ date.day }}</view>
                        <view class="date-date">{{ date.date }}</view>
                      </view>
                    </view>
                  </scroll-view>
                </view>

                <!-- 时间段选择 -->
                <view class="time-selector">
                  <view class="time-title ss-m-b-20">选择时间段（可多选）</view>

                  <!-- 加载状态 -->
                  <view v-if="state.loadingAvailability" class="loading-container">
                    <view class="loading-content">
                      <view class="loading-spinner"></view>
                      <text class="loading-text">正在查询可预约时间人数...</text>
                    </view>
                  </view>

                  <!-- 时间段网格 -->
                  <view v-else class="time-grid">
                    <view
                      v-for="timeSlot in state.availableTimes"
                      :key="timeSlot.value"
                      class="time-item"
                      :class="[
                        {
                          'active': isTimeSelected(timeSlot.value),
                          'disabled': !state.selectedDate || !isTimeSlotAvailable(timeSlot)
                        },
                        `status-${getTimeSlotStatus(timeSlot)}`
                      ]"
                      @tap="state.selectedDate && isTimeSlotAvailable(timeSlot) ? selectTime(timeSlot.value) : null"
                    >
                      <view class="time-label">{{ timeSlot.label }}</view>
                      <view class="time-value">{{ timeSlot.value }}</view>
                      <view class="time-availability" v-if="state.selectedDate">
                        {{ getTimeSlotInfo(timeSlot) }}
                      </view>

                      <!-- 状态图标 -->
                      <view class="status-icon" v-if="getTimeSlotStatus(timeSlot) === 'leave'">
                        <text class="icon-text">请假</text>
                      </view>
                      <view class="status-icon" v-else-if="getTimeSlotStatus(timeSlot) === 'full'">
                        <text class="icon-text">约满</text>
                      </view>
                      <view class="status-icon warning" v-else-if="getTimeSlotStatus(timeSlot) === 'warning'">
                        <text class="icon-text">!</text>
                      </view>
                    </view>
                  </view>

                  <view class="time-tip ss-m-t-16" v-if="!state.selectedDate">
                    <text class="tip-text">请先选择预约日期</text>
                  </view>
                </view>

                <view class="selected-times ss-m-t-20" v-if="state.selectedTimes.length > 0">
                  <view class="selected-title">已选择时间段：</view>
                  <view class="selected-list">
                    <view
                      v-for="timeValue in state.selectedTimes"
                      :key="timeValue"
                      class="selected-tag"
                    >
                      {{ getTimeLabelByValue(timeValue) }}
                      <text class="remove-btn" @tap.stop="selectTime(timeValue)">×</text>
                    </view>
                  </view>

                  <!-- 显示合并后的预约时间段 -->
                  <view class="merged-times ss-m-t-16" v-if="getMergedTimeSlots().length !== state.selectedTimes.length">
                    <view class="merged-title">将合并为：</view>
                    <view class="merged-list">
                      <view
                        v-for="(mergedSlot, index) in getMergedTimeSlots()"
                        :key="index"
                        class="merged-tag"
                      >
                        {{ mergedSlot.label }}
                      </view>
                    </view>
                  </view>
                </view>

                <button
                  class="confirm-btn ss-m-t-40"
                  :disabled="!state.selectedDate || state.selectedTimes.length === 0"
                  @tap="confirmBooking"
                >
                  {{ !state.selectedDate ? '请先选择日期' :
                     state.selectedTimes.length === 0 ? '请选择时间段' :
                     `确认预约 (${state.selectedTimes.length}个时间段)` }}
                </button>
              </view>
            </view>
          </su-popup>
        </view>

        <!-- 详情 -->
        <view class="detail-content-card detail-card ss-p-30" v-if="state.coachInfo.description">
          <view class="detail-content-title ss-m-b-20">教练详情</view>
          <view class="detail-content">
            <rich-text :nodes="state.coachInfo.description"></rich-text>
          </view>
        </view>

        <!-- 详情 tabbar -->
        <su-fixed bottom placeholder>
          <view class="coach-tabbar-box">
            <view class="tabbar-left ss-flex ss-col-center">
              <!-- 收藏 -->
              <view class="action-btn ss-flex ss-flex-col ss-col-center ss-row-center" @tap="onFavorite">
                <text class="sicon-star" :class="{ 'favorited': state.coachInfo.favorite }"></text>
                <text class="action-title">{{ state.coachInfo.favorite ? '已收藏' : '收藏' }}</text>
              </view>

              <!-- 分享 -->
              <view class="action-btn ss-flex ss-flex-col ss-col-center ss-row-center" @tap="onShare">
                <text class="sicon-share"></text>
                <text class="action-title">分享</text>
              </view>
            </view>

            <view class="tabbar-right ss-flex-1 ss-flex ss-col-center ss-p-l-20">
              <view class="buy-box ss-flex ss-col-center">
                <button
                  class="ss-reset-button booking-btn ui-Shadow-Main"
                  @tap="openTimeSelectModal"
                >
                  立即预约
                </button>
              </view>
            </view>
          </view>
        </su-fixed>
      </block>
    </s-layout>
  </view>
</template>

<script setup>
  import { reactive, computed } from 'vue';
  import { onLoad } from '@dcloudio/uni-app';
  import sheep from '@/sheep';
  import {
    formatSales,
    formatGoodsSwiper,
    fen2yuan,
  } from '@/sheep/hooks/useGoods';
  import { isEmpty } from 'lodash-es';
  import SpuApi from '@/sheep/api/product/spu';
  import FavoriteApi from '@/sheep/api/product/favorite';
  import ScheduleBookingApi from '@/sheep/api/system/schedule-booking';
  import { SharePageEnum } from '@/sheep/helper/const';

  const isLogin = computed(() => sheep.$store('user').isLogin);

  // 生成可预约日期（今天到未来30天）
  const generateAvailableDates = () => {
    const dates = [];
    const today = new Date();

    for (let i = 0; i < 31; i++) {
      const date = new Date(today);
      date.setDate(today.getDate() + i);

      const dayNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
      const month = date.getMonth() + 1;
      const day = date.getDate();

      dates.push({
        value: `${date.getFullYear()}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`,
        day: i === 0 ? '今天' : dayNames[date.getDay()],
        date: `${month}/${day}`
      });
    }

    state.availableDates = dates;
  };

  // 打开预约时间选择弹窗
  const openTimeSelectModal = () => {
    state.showTimeSelect = true;

    // 默认选择明天
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    const tomorrowStr = `${tomorrow.getFullYear()}-${(tomorrow.getMonth() + 1).toString().padStart(2, '0')}-${tomorrow.getDate().toString().padStart(2, '0')}`;

    // 检查明天是否在可选日期列表中
    const tomorrowExists = state.availableDates.find(d => d.value === tomorrowStr);
    if (tomorrowExists) {
      // 自动选择明天
      selectDate(tomorrowStr);
    } else if (state.availableDates.length > 0) {
      // 如果明天不在列表中，选择第一个可用日期
      selectDate(state.availableDates[0].value);
    }
  };

  // 选择日期
  const selectDate = async (date) => {
    state.selectedDate = date;
    state.selectedTimes = []; // 重置时间选择
    state.timeSlotAvailability = {}; // 清空之前的可预约信息

    // 查询该日期的可预约人数
    await loadCoachAvailability(date);
  };

  // 查询教练可预约人数
  const loadCoachAvailability = async (date) => {
    if (!date || !state.coachId) {
      return;
    }

    state.loadingAvailability = true;

    try {
      const params = {
        coachId: state.coachId,
        date: date
      };

      // 创建一个带超时的Promise
      const timeoutPromise = new Promise((_, reject) => {
        setTimeout(() => reject(new Error('请求超时')), 10000); // 10秒超时
      });

      const apiPromise = ScheduleBookingApi.getCoachAvailability(params);

      // 使用Promise.race来实现超时控制
      const { data } = await Promise.race([apiPromise, timeoutPromise]);

      if (data && data.timeSlots) {
        // 将时间段可预约信息存储到状态中
        const availability = {};
        data.timeSlots.forEach(slot => {
          availability[slot.timeSlotType] = {
            availableCount: slot.availableCount,
            maxCount: slot.maxCount,
            available: slot.available,
            unavailableReason: slot.unavailableReason
          };
        });
        state.timeSlotAvailability = availability;
      } else {
        // 如果没有返回数据，设置默认状态
        console.warn('未获取到可预约信息');
        uni.showToast({
          title: '未获取到可预约信息',
          icon: 'none',
        });
      }
    } catch (error) {
      console.error('查询可预约人数失败:', error);

      let errorMsg = '查询可预约信息失败';
      if (error.message === '请求超时') {
        errorMsg = '查询超时，请重试';
      } else if (error.code === 'NETWORK_ERROR') {
        errorMsg = '网络连接失败，请检查网络';
      }

      uni.showToast({
        title: errorMsg,
        icon: 'none',
        duration: 3000
      });
    } finally {
      state.loadingAvailability = false;
    }
  };
  const state = reactive({
    coachId: 0,
    coachInfo: {},
    showTimeSelect: false,
    selectedSku: {},
    selectedDate: '', // 选中的日期
    selectedTimes: [], // 改为数组支持多选
    availableDates: [], // 可选日期列表
    availableTimes: [
      { label: '8-10点', value: '08:00-10:00', startTime: '08:00', endTime: '10:00', timeSlotType: 1 },
      { label: '10-12点', value: '10:00-12:00', startTime: '10:00', endTime: '12:00', timeSlotType: 2 },
      { label: '14-16点', value: '14:00-16:00', startTime: '14:00', endTime: '16:00', timeSlotType: 3 },
      { label: '16-18点', value: '16:00-18:00', startTime: '16:00', endTime: '18:00', timeSlotType: 4 }
    ],
    timeSlotAvailability: {}, // 存储时间段可预约信息
    loadingAvailability: false, // 加载可预约信息状态
  });

  // 选择时间（支持多选）
  const selectTime = (timeValue) => {
    // 找到对应的时间段
    const timeSlot = state.availableTimes.find(t => t.value === timeValue);
    if (!timeSlot) return;

    // 检查是否可预约
    if (!isTimeSlotAvailable(timeSlot)) {
      uni.showToast({
        title: '该时间段不可预约',
        icon: 'none',
      });
      return;
    }

    const index = state.selectedTimes.indexOf(timeValue);
    if (index > -1) {
      // 如果已选中，则取消选择
      state.selectedTimes.splice(index, 1);
    } else {
      // 如果未选中，则添加到选择列表
      state.selectedTimes.push(timeValue);
    }
  };

  // 判断时间是否已选中
  const isTimeSelected = (timeValue) => {
    return state.selectedTimes.includes(timeValue);
  };

  // 判断时间段是否可预约
  const isTimeSlotAvailable = (timeSlot) => {
    // 如果正在加载，所有时间段都不可选
    if (state.loadingAvailability) {
      return false;
    }

    const availability = state.timeSlotAvailability[timeSlot.timeSlotType];
    return availability ? availability.available : false; // 没有数据时不可预约
  };

  // 获取时间段可预约人数信息
  const getTimeSlotInfo = (timeSlot) => {
    // 如果正在加载，不显示任何信息
    if (state.loadingAvailability) {
      return '';
    }

    const availability = state.timeSlotAvailability[timeSlot.timeSlotType];
    if (!availability) {
      return '';
    }

    if (!availability.available) {
      return availability.unavailableReason || '(不可预约)';
    }

    return `(${availability.availableCount}/${availability.maxCount})`;
  };

  // 获取时间段状态类型
  const getTimeSlotStatus = (timeSlot) => {
    if (state.loadingAvailability) {
      return 'loading';
    }

    const availability = state.timeSlotAvailability[timeSlot.timeSlotType];
    if (!availability) {
      return 'unknown';
    }

    if (!availability.available) {
      // 根据不可预约原因判断状态类型
      const reason = availability.unavailableReason || '';
      if (reason.includes('请假') || reason.includes('休息')) {
        return 'leave'; // 请假状态
      } else if (availability.availableCount === 0) {
        return 'full'; // 已约满状态
      } else {
        return 'unavailable'; // 其他不可预约状态
      }
    }

    // 可预约状态，但人数较少时显示警告
    if (availability.availableCount <= 2) {
      return 'warning'; // 人数不足警告
    }

    return 'available'; // 正常可预约
  };

  // 根据时间值获取时间标签
  const getTimeLabelByValue = (timeValue) => {
    const timeObj = state.availableTimes.find(t => t.value === timeValue);
    return timeObj ? timeObj.label : timeValue;
  };

  // 获取选中时间的显示文本
  const getSelectedTimesText = () => {
    if (!state.selectedDate && state.selectedTimes.length === 0) {
      return '请选择预约日期和时间段';
    }
    if (!state.selectedDate) {
      return '请选择预约日期';
    }
    if (state.selectedTimes.length === 0) {
      return `${getDateLabel(state.selectedDate)} - 请选择时间段`;
    }
    const labels = state.selectedTimes.map(timeValue => getTimeLabelByValue(timeValue));
    return `${getDateLabel(state.selectedDate)} - ${labels.join('、')}`;
  };

  // 根据日期值获取日期标签
  const getDateLabel = (dateValue) => {
    const dateObj = state.availableDates.find(d => d.value === dateValue);
    return dateObj ? `${dateObj.date}(${dateObj.day})` : dateValue;
  };

  // 获取合并后的时间段（用于预览）
  const getMergedTimeSlots = () => {
    return mergeTimeSlots(state.selectedTimes);
  };

  // 合并连续的时间段
  const mergeTimeSlots = (selectedTimes) => {
    if (selectedTimes.length === 0) return [];

    // 获取时间段对象并按开始时间排序
    const timeObjects = selectedTimes
      .map(timeValue => state.availableTimes.find(t => t.value === timeValue))
      .filter(Boolean)
      .sort((a, b) => a.startTime.localeCompare(b.startTime));

    const mergedSlots = [];
    let currentSlot = { ...timeObjects[0] };

    for (let i = 1; i < timeObjects.length; i++) {
      const nextSlot = timeObjects[i];

      // 检查当前时间段的结束时间是否等于下一个时间段的开始时间
      if (currentSlot.endTime === nextSlot.startTime) {
        // 连续时间段，合并
        currentSlot.endTime = nextSlot.endTime;
        currentSlot.label = `${currentSlot.label.split('-')[0]}-${nextSlot.label.split('-')[1]}`;
        currentSlot.value = `${currentSlot.startTime}-${currentSlot.endTime}`;
      } else {
        // 不连续，保存当前时间段，开始新的时间段
        mergedSlots.push(currentSlot);
        currentSlot = { ...nextSlot };
      }
    }

    // 添加最后一个时间段
    mergedSlots.push(currentSlot);

    return mergedSlots;
  };

  // 确认预约
  const confirmBooking = async () => {
    if (!state.selectedDate) {
      sheep.$helper.toast('请选择预约日期');
      return;
    }

    if (state.selectedTimes.length === 0) {
      sheep.$helper.toast('请选择预约时间');
      return;
    }

    if (!isLogin.value) {
      sheep.$helper.toast('请先登录');
      return;
    }

    try {
      // 获取当前用户ID
      const userId = sheep.$store('user').userInfo?.id;
      if (!userId) {
        sheep.$helper.toast('用户信息获取失败，请重新登录');
        return;
      }

      // 合并连续的时间段
      const mergedTimeSlots = mergeTimeSlots(state.selectedTimes);

      console.log('原始选择:', state.selectedTimes);
      console.log('合并后的时间段:', mergedTimeSlots);

      // 为每个合并后的时间段创建预约记录
      const bookingResults = [];

      for (const timeSlot of mergedTimeSlots) {
        const bookingData = {
          userId: userId,
          coachId: parseInt(state.coachId),
          bookingDate: state.selectedDate,
          startTime: timeSlot.startTime,
          endTime: timeSlot.endTime,
        };

        console.log('提交预约数据:', bookingData);

        try {
          const result = await ScheduleBookingApi.createScheduleBooking(bookingData);

          // 检查返回结果
          if (result.code !== 0) {
            // 接口返回错误码，抛出错误
            throw new Error(result.msg || '预约失败');
          }

          bookingResults.push(result);
        } catch (apiError) {
          // 如果是接口返回的业务错误，直接抛出
          if (apiError.code || apiError.msg) {
            throw apiError;
          }
          // 如果是网络错误等，包装后抛出
          throw new Error(apiError.message || '网络请求失败');
        }
      }

      // 所有预约都成功
      state.showTimeSelect = false;

      // 显示成功信息
      const mergedLabels = mergedTimeSlots.map(slot => slot.label);
      uni.showToast({
        title: `预约成功！时间：${mergedLabels.join('、')}`,
        icon: 'success',
        duration: 3000
      });

      // 重置选择状态
      state.selectedDate = '';
      state.selectedTimes = [];

    } catch (error) {
      console.error('预约失败:', error);

      // 显示错误信息，优先使用后端返回的msg
      let errorMsg = '预约失败，请稍后重试';

      if (error.msg) {
        errorMsg = error.msg; // 后端返回的具体错误信息
      } else if (error.message) {
        errorMsg = error.message; // 其他错误信息
      }

      uni.showToast({
        title: errorMsg,
        icon: 'none',
        duration: 4000 // 错误信息显示时间稍长一些
      });
    }
  };

  // 收藏/取消收藏
  const onFavorite = async () => {
    if (!isLogin.value) {
      sheep.$helper.toast('请先登录');
      return;
    }

    const isFavorited = state.coachInfo.favorite;
    let result;

    if (isFavorited) {
      result = await FavoriteApi.deleteFavorite(state.coachInfo.id, 'goods');
    } else {
      result = await FavoriteApi.createFavorite(state.coachInfo.id, 'goods');
    }

    if (result.code === 0) {
      state.coachInfo.favorite = !isFavorited;

      uni.showToast({
        title: isFavorited ? '取消收藏' : '收藏成功',
        icon: 'success',
      });
    }
  };

  // 分享
  const onShare = () => {
    sheep.$platform.share.show();
  };

  const shareInfo = computed(() => {
    if (isEmpty(state.coachInfo)) return {};
    return sheep.$platform.share.getShareInfo(
      {
        title: `预约教练：${state.coachInfo.name}`,
        image: sheep.$url.cdn(state.coachInfo.picUrl),
        desc: state.coachInfo.introduction,
        params: {
          page: SharePageEnum.GOODS.value,
          query: state.coachInfo.id,
        },
      },
      {
        type: 'coach',
        title: state.coachInfo.name,
        image: sheep.$url.cdn(state.coachInfo.picUrl),
        price: fen2yuan(state.coachInfo.price),
      },
    );
  });

  onLoad((options) => {
    // 非法参数
    if (!options.id) {
      state.coachInfo = null;
      return;
    }
    state.coachId = options.id;

    // 生成可预约日期
    generateAvailableDates();

    // 1. 加载教练信息（复用商品接口）
    SpuApi.getSpuDetail(state.coachId).then((res) => {
      if (res.code !== 0 || !res.data) {
        state.coachInfo = null;
        return;
      }
      // 加载到教练信息
      state.coachInfo = res.data;
      state.selectedSku = res.data.skus?.[0] || {};

      // 加载是否收藏
      if (isLogin.value) {
        FavoriteApi.isFavoriteExists(state.coachId, 'goods').then((res) => {
          if (res.code !== 0) {
            return;
          }
          state.coachInfo.favorite = res.data;
        });
      }
    });
  });
</script>

<style lang="scss" scoped>
.detail-card {
  background-color: #ffffff;
  margin: 14rpx 20rpx;
  border-radius: 16rpx;
  overflow: hidden;
}

// 教练信息卡片
.coach-card {
  .coach-info {
    flex: 1;
    
    .coach-avatar {
      width: 120rpx;
      height: 120rpx;
      border-radius: 60rpx;
      border: 4rpx solid #f0f0f0;
    }
    
    .coach-details {
      flex: 1;
      
      .coach-name {
        font-size: 36rpx;
        font-weight: 600;
        color: #333333;
        margin-bottom: 8rpx;
      }
      
      .coach-experience {
        font-size: 26rpx;
        color: #666666;
        line-height: 1.4;
        margin-bottom: 8rpx;
      }
      
      .coach-rating {
        .rating-stars {
          .star-icon {
            font-size: 24rpx;
            color: #ddd;
            margin-right: 4rpx;
            
            &.active {
              color: #ffa500;
            }
          }
        }
        
        .rating-text {
          font-size: 24rpx;
          color: #666666;
        }
        
        .student-count {
          font-size: 24rpx;
          color: #999999;
        }
      }
    }
  }
  
  .price-box {
    .price-text {
      font-size: 42rpx;
      font-weight: 500;
      color: #ff3000;
      line-height: 30rpx;
      font-family: OPPOSANS;

      &::before {
        content: '￥';
        font-size: 30rpx;
      }
    }
    
    .price-unit {
      font-size: 24rpx;
      color: #999999;
      margin-top: 4rpx;
    }
  }
  
  .coach-tags {
    .tag {
      padding: 8rpx 16rpx;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: #ffffff;
      font-size: 22rpx;
      border-radius: 20rpx;
      margin-right: 16rpx;
    }
  }
}

// 功能卡片
.cell-box {
  height: 120rpx;
  padding: 0 30rpx;
  background: #fff;
  position: relative;

  .cell-mmm {
    flex: 1;
  }

  .cell-title {
    font-size: 30rpx;
    font-weight: 500;
    color: #333;
    margin-bottom: 10rpx;
  }

  .cell-desc {
    font-size: 26rpx;
    color: #999;
  }

  .cicon-forward {
    color: #c4c4c4;
    font-size: 32rpx;
  }

  &::after {
    position: absolute;
    content: '';
    border-bottom: 2rpx solid #f2f2f2;
    transform: scaleY(0.5);
    bottom: 0;
    right: 0;
    left: 30rpx;
  }
}

// 详情内容
.detail-content-card {
  .detail-content-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333333;
    position: relative;
    padding-left: 20rpx;
    
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 6rpx;
      height: 32rpx;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border-radius: 3rpx;
    }
  }

  .detail-content {
    font-size: 28rpx;
    line-height: 1.8;
    color: #666;
    word-break: break-all;
  }
}

// 底部操作栏
.coach-tabbar-box {
  display: flex;
  align-items: center;
  height: 100rpx;
  background: #ffffff;
  border-top: 1rpx solid #f0f0f0;
  padding: 0 20rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.tabbar-left {
  .action-btn {
    width: 80rpx;
    height: 80rpx;
    margin-right: 20rpx;

    .sicon-star,
    .sicon-share {
      font-size: 36rpx;
      color: #666666;
      margin-bottom: 4rpx;
      transition: all 0.3s ease;

      &.favorited {
        color: #ff6b35;
      }
    }

    .action-title {
      font-size: 20rpx;
      color: #999999;
      line-height: 1;
    }

    &:active {
      transform: scale(0.95);
    }
  }
}

.tabbar-right {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

// 预约按钮
.buy-box {
  .booking-btn {
    width: 428rpx;
    height: 72rpx;
    font-weight: 600;
    font-size: 32rpx;
    border-radius: 40rpx;
    background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
    color: #ffffff;
  }
}

// 预约时间选择弹窗
.time-select-popup {
  background: #ffffff;
  border-radius: 20rpx 20rpx 0 0;
  max-height: 80vh;
  
  .popup-header {
    border-bottom: 1rpx solid #f0f0f0;
    
    .popup-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333333;
    }
    
    .close-btn {
      font-size: 32rpx;
      color: #999999;
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  
  .time-content {
    .date-selector {
      .date-title {
        font-size: 28rpx;
        font-weight: 600;
        color: #333333;
      }

      .date-scroll {
        white-space: nowrap;

        .date-list {
          .date-item {
            flex-shrink: 0;
            width: 120rpx;
            padding: 20rpx 0;
            text-align: center;
            border-radius: 12rpx;
            margin-right: 16rpx;
            transition: all 0.3s ease;
            background: #f8f9fa;

            .date-day {
              font-size: 22rpx;
              color: #999999;
              margin-bottom: 8rpx;
            }

            .date-date {
              font-size: 28rpx;
              font-weight: 500;
              color: #333333;
            }

            &.active {
              background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

              .date-day,
              .date-date {
                color: #ffffff;
              }
            }
          }
        }
      }
    }

    .time-selector {
      .time-title {
        font-size: 28rpx;
        font-weight: 600;
        color: #333333;
      }
      
      .loading-container {
        display: flex;
        justify-content: center;
        align-items: center;
        min-height: 200rpx;

        .loading-content {
          display: flex;
          flex-direction: column;
          align-items: center;

          .loading-spinner {
            width: 40rpx;
            height: 40rpx;
            border: 4rpx solid #f0f0f0;
            border-top: 4rpx solid #1890ff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 16rpx;
          }

          .loading-text {
            font-size: 26rpx;
            color: #666666;
          }
        }
      }

      @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
      }

      .time-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 16rpx;

        .time-item {
          padding: 20rpx 16rpx;
          text-align: center;
          background: #f8f9fa;
          border-radius: 12rpx;
          transition: all 0.3s ease;
          border: 2rpx solid transparent;
          position: relative;

          .time-label {
            font-size: 28rpx;
            font-weight: 600;
            color: #333333;
            margin-bottom: 6rpx;
          }

          .time-value {
            font-size: 22rpx;
            color: #666666;
            margin-bottom: 4rpx;
          }

          .time-availability {
            font-size: 20rpx;
            color: #999999;
          }

          .status-icon {
            position: absolute;
            top: 6rpx;
            right: 6rpx;
            width: 32rpx;
            height: 20rpx;
            border-radius: 10rpx;
            display: flex;
            align-items: center;
            justify-content: center;

            .icon-text {
              font-size: 18rpx;
              font-weight: 600;
              color: #ffffff;
            }

            &:not(.warning) {
              background: #ff4d4f;
            }

            &.warning {
              background: #faad14;
              width: 20rpx;
              height: 20rpx;
              border-radius: 50%;

              .icon-text {
                font-size: 14rpx;
              }
            }
          }

          // 正常可预约状态
          &.status-available {
            background: #f8f9fa;
            border-color: transparent;
          }

          // 人数不足警告状态
          &.status-warning {
            background: #fff7e6;
            border-color: #ffd591;

            .time-availability {
              color: #fa8c16;
              font-weight: 600;
            }
          }

          // 请假状态 - 红色警告
          &.status-leave {
            background: #fff2f0;
            border-color: #ffccc7;

            .time-label,
            .time-value {
              color: #ff4d4f;
            }

            .time-availability {
              color: #ff4d4f;
              font-weight: 600;
            }
          }

          // 已约满状态 - 红色警告
          &.status-full {
            background: #fff2f0;
            border-color: #ffccc7;

            .time-label,
            .time-value {
              color: #ff4d4f;
            }

            .time-availability {
              color: #ff4d4f;
              font-weight: 600;
            }
          }

          // 其他不可预约状态
          &.status-unavailable {
            background: #f5f5f5;
            border-color: #d9d9d9;

            .time-label,
            .time-value,
            .time-availability {
              color: #8c8c8c;
            }
          }

          &.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-color: #667eea;
            transform: scale(1.02);

            .time-label,
            .time-value,
            .time-availability {
              color: #ffffff;
            }

            .status-icon {
              display: none; // 选中时隐藏状态图标
            }

            &::after {
              content: '✓';
              position: absolute;
              top: 8rpx;
              right: 8rpx;
              width: 24rpx;
              height: 24rpx;
              background: rgba(255, 255, 255, 0.9);
              color: #667eea;
              border-radius: 50%;
              font-size: 16rpx;
              font-weight: 600;
              display: flex;
              align-items: center;
              justify-content: center;
            }
          }

          &.disabled {
            opacity: 0.6;
            cursor: not-allowed;
          }

          &:not(.disabled):not(.status-leave):not(.status-full):not(.status-unavailable):active {
            transform: scale(0.98);
          }
        }
      }

      .time-tip {
        text-align: center;

        .tip-text {
          font-size: 24rpx;
          color: #999999;
        }
      }
    }

    .selected-times {
      .selected-title {
        font-size: 26rpx;
        font-weight: 600;
        color: #333333;
        margin-bottom: 16rpx;
      }

      .selected-list {
        display: flex;
        flex-wrap: wrap;
        gap: 12rpx;

        .selected-tag {
          display: flex;
          align-items: center;
          padding: 8rpx 16rpx;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          color: #ffffff;
          font-size: 24rpx;
          border-radius: 20rpx;

          .remove-btn {
            margin-left: 8rpx;
            width: 20rpx;
            height: 20rpx;
            background: rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            font-size: 16rpx;
            font-weight: 600;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;

            &:active {
              background: rgba(255, 255, 255, 0.5);
            }
          }
        }
      }

      .merged-times {
        .merged-title {
          font-size: 24rpx;
          font-weight: 600;
          color: #667eea;
          margin-bottom: 12rpx;
        }

        .merged-list {
          display: flex;
          flex-wrap: wrap;
          gap: 12rpx;

          .merged-tag {
            padding: 8rpx 16rpx;
            background: linear-gradient(135deg, #00f2fe 0%, #4facfe 100%);
            color: #ffffff;
            font-size: 24rpx;
            border-radius: 20rpx;
            font-weight: 500;
          }
        }
      }
    }

    .confirm-btn {
      width: 100%;
      height: 88rpx;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: #ffffff;
      font-size: 32rpx;
      font-weight: 600;
      border-radius: 12rpx;
      border: none;
      transition: all 0.3s ease;

      &:disabled {
        background: #cccccc;
        color: #ffffff;
        opacity: 0.6;
      }

      &:not(:disabled):active {
        transform: scale(0.98);
      }
    }
  }
}
</style>
